package net.yambal.mobile.adv.managed_component
{
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.events.TouchEvent;
	import flash.geom.Rectangle;
	import flash.utils.Timer;
	
	import mx.collections.ArrayCollection;
	import mx.events.EffectEvent;
	import mx.events.FlexEvent;
	
	import net.yambal.mobile.adv.ADV_Chapter;
	import net.yambal.mobile.adv.ADV_Paragraph;
	import net.yambal.mobile.adv.ADV_SelectItemOption;
	import net.yambal.mobile.adv.IADV_ParagraphItem;
	import net.yambal.mobile.adv.managed_component.base.ADV_ViewBase;
	
	import spark.components.Group;
	import spark.components.Image;
	import spark.components.List;
	import spark.components.TextArea;
	import spark.components.View;
	import spark.effects.Fade;
	import spark.events.IndexChangeEvent;
	import spark.filters.DropShadowFilter;
	
	public class ADV_StoryView extends ADV_ViewBase
	{
		private var _currentChapter:ADV_Chapter = null;
		private var _currentChapterID:String = null;
		
		private var _currentParagraph:ADV_Paragraph = null;
		private var _currentParagraphID:String = null;
		
		private var _currentParagraphNum:Number = 0;
		
		public var seen_size_width:Number = 480;
		public var seen_size_height:Number = 320;
		
		public var wrapper_group:Group = null;
		public var text_area:TextArea = null;
		public var list:List = null;
		public var seen_img:Image = null;
		public var frame_img:Image = null;

		
		[Bindable]
		public var _list_source:ArrayCollection = null;
		
		public function ADV_StoryView()
		{
			super();
		}
		
		// IADV_View
		override public function ADV_onCreationComplete(e:FlexEvent):void{
			trace(this + ":ADV_onCreationComplete");
			removeEventListener(FlexEvent.CREATION_COMPLETE, ADV_onCreationComplete);
			setSeenSize();
			app_mng.story.onStoryViewCreateComplete(this);
		}
		
		override public function get type():String{
			return "story";
		}

		override public function onClickMenuBtn():void{
			trace(this + ":onClickMenuBtn");
		}
		
		override public function onClickBackBtn():void{
			trace(this + ":onClickBackBtn");
		}
		
		override public function onClickSearchBtn():void{
			trace(this + ":onClickSearchBtn");
		}
		
		/**
		 * 
		 **/
		private function setSeenSize():void{
			//
			wrapper_group.width = app_mng.horizontal_width;
			wrapper_group.height = app_mng.horizontal_height;
			
			var zoom:Number = app_mng.horizontal_height / seen_size_height;
			if(app_mng.app_width / seen_size_width > zoom){
				zoom = app_mng.horizontal_width / seen_size_width;
			}
			seen_img.width = Math.round(seen_size_width * zoom) + 2;
			seen_img.height = Math.round(seen_size_height * zoom) + 2;
			seen_img.x = (app_mng.horizontal_width - seen_img.width) / 2;
			seen_img.y = (app_mng.horizontal_height - seen_img.height) / 2;
	
			var tf:DropShadowFilter  = new DropShadowFilter(0,0,0x000000,1,6,6,5,1,false,false);
			text_area.filters = [tf];

			list.visible = false;
		}

		public function pushChapterParagraph(chapter_id:String, paragraph_id:String = null, option:Object = null):void{
			if(paragraph_id == null){
				var chapter:ADV_Chapter = app_mng.story.getChapter(chapter_id);
				paragraph_id = chapter.start_paragraph_id;
			}
			trace(this + ":pushChapterParagraph" +
				"\n\tchapter_id:" + chapter_id +
				"\n\tparagraph_id:" + paragraph_id);
			
			var oldChapID:String = _currentChapterID;
			var oldPID:String = _currentParagraphID;
			
			if(oldChapID == null || oldChapID != chapter_id){
				changeChapter(chapter_id, paragraph_id);
				
			}else if(oldPID == null || oldPID != paragraph_id){
				changeParagraph(chapter_id, paragraph_id);
				
			}else{
				trace("\tno change");
			}
		}
		
		// ****************************************************************************
		/**
		 * Chapterを更新する
		 * （必然的にParagraphも更新する）
		 **/
		private function changeChapter(chapter_id:String, paragraph_id:String):void{
			trace("\t\tchangeChapter");
			
			_currentChapterID = chapter_id;
			_currentChapter = app_mng.story.getChapter(_currentChapterID);
			
			changeSeenImage(chapter_id, paragraph_id);
		}
		
		// Fade-In Fade-Out - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
		private var _fade_wait_chapter_id:String = null;
		private var _fade_wait_paragraph_id:String = null;
		
		private function changeSeenImage(chapter_id:String, paragraph_id:String):void{
			_fade_wait_chapter_id = chapter_id;
			_fade_wait_paragraph_id = paragraph_id;
			
			var fade_out:Fade = new Fade();
			fade_out.alphaFrom = seen_img.alpha;
			fade_out.alphaTo = 0;
			fade_out.addEventListener(EffectEvent.EFFECT_END, onSeenImgFadeOut);

			fade_out.play([wrapper_group]);
		}
		
		// Fade-Out
		private function onSeenImgFadeOut(e:EffectEvent):void{
			var fade_out:Fade = e.currentTarget as Fade;
			fade_out.removeEventListener(EffectEvent.EFFECT_END, onSeenImgFadeOut);
			
			wrapper_group.alpha = 0;
			
			text_area.text = "";
			text_area.alpha = 0;
			
			seen_img.source = _currentChapter.seen_img_obj;
			frame_img.source = _currentChapter.frame_img_obj;
				
			var fade_in:Fade = new Fade();
			fade_in.alphaFrom = 0;
			fade_in.alphaTo = 1;
			fade_in.addEventListener(EffectEvent.EFFECT_END, onSeenImgFadeIN);
			
			fade_in.play([wrapper_group]);
		}
		
		// Fade-In
		private function onSeenImgFadeIN(e:EffectEvent):void{
			var fade_in:Fade = e.currentTarget as Fade;
			fade_in.removeEventListener(EffectEvent.EFFECT_END, onSeenImgFadeIN);
			
			startTimerAfterShowImgShow(_currentChapter.text_rag);
		}
		
		// 背景が表示された後のWait - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
		private var _timerAfterShowImg:Timer = null;
		private function startTimerAfterShowImgShow(sec:Number):void{
			stopTimerAfterShowImgShow();
			_timerAfterShowImg = new Timer(sec * 1000);
			
			_timerAfterShowImg.addEventListener(TimerEvent.TIMER, onTimetAfterSeenImgShow);
			_timerAfterShowImg.start();
			
		}
		
		private function stopTimerAfterShowImgShow():void{
			if(_timerAfterShowImg != null){
				_timerAfterShowImg.removeEventListener(TimerEvent.TIMER, onTimetAfterSeenImgShow);
				_timerAfterShowImg.stop();
				_timerAfterShowImg.reset();
				_timerAfterShowImg = null;
			}
		}
		
		private function onTimetAfterSeenImgShow(e:TimerEvent):void{
			stopTimerAfterShowImgShow();
			changeParagraph(_fade_wait_chapter_id, _fade_wait_paragraph_id);
			
			_fade_wait_chapter_id = null;
			_fade_wait_paragraph_id = null;
		}
		
		/**
		 * Paragraphを更新する
		 **/
		private function changeParagraph(chapter_id:String, paragraph_id:String):void{
			trace("\t\tchangeParagraph");
			
			_currentParagraphID = paragraph_id;
			_currentParagraph = _currentChapter.getParagraph(paragraph_id);
			
			_currentParagraphNum = -1;
			
			showNextParagraphItem();
		}
		
		// 
		private var _currentParagraphItem:IADV_ParagraphItem = null;
		
		private function showNextParagraphItem():void{
			trace("showNextParagraphItem");
			
			list.visible = false;
			
			if(_currentParagraphNum < _currentParagraph.items.length - 1 ){
				_currentParagraphNum ++;
				_currentParagraphItem = _currentParagraph.items[_currentParagraphNum];
				
				trace("\tタイプ:" + _currentParagraphItem.type);
				setParagraphText(_currentParagraphItem.text);
				
			}else{
				// paragraph最後のtextでtep
				trace("paragraph最後のtextでtap" + _currentChapterID);
				
				if(_currentParagraph.next_chapter_id == null && _currentParagraph.next_paragraph_id != null){
					trace("\tParagraphのみ指定(" + _currentParagraph.next_paragraph_id + ")" +
						"\t同じCapture("+_currentChapterID+")内のParagraph("+_currentParagraph.next_paragraph_id+")に移動");
					app_mng.story.goto(_currentChapterID, _currentParagraph.next_paragraph_id);
					
				}else if(_currentParagraph.next_chapter_id != null){
					trace("\tCapture指定("+_currentParagraph.next_chapter_id+")" +
						"\tParagraph指定("+_currentParagraph.next_paragraph_id+")");
					
					app_mng.story.goto(_currentParagraph.next_chapter_id, _currentParagraph.next_paragraph_id);
					
				}else{
					trace("Error");
				}
			}
		}
		
		// タップしたら次のParagraphItemを表示 ------------------------------------
		/**
		 * add Listener
		 **/
		private function TapThenShowNextParagraphItem():void{
			stopTapListenerForShowNextParagraphItem();
			addEventListener(TouchEvent.TOUCH_TAP, onTapForShowNextParagraphItem);
			addEventListener(MouseEvent.CLICK, onTapForShowNextParagraphItem);
		}
		
		/**
		 * タップしたら
		 **/
		private function onTapForShowNextParagraphItem(e:Object):void{
			stopTapListenerForShowNextParagraphItem();
			if(_is_pre_text){
				onShowPreText();
			}else{
				showNextParagraphItem();
			}
		}
		
		/**
		 * remove Listener
		 **/
		private function stopTapListenerForShowNextParagraphItem():void{
			removeEventListener(TouchEvent.TOUCH_TAP, onTapForShowNextParagraphItem);
			removeEventListener(MouseEvent.CLICK, onTapForShowNextParagraphItem);
		}
		
		// Text *******************************************************************************
		private var timerShowParagraphTextRag:Timer = null;
		private var _paragraphText:String;
		private var _paragraphTextNum:Number;
		
		/**
		 * （タイマーで）テキストをラグを持たせて表示
		 * add Listener
		 **/
		private function setParagraphText(text:String):void{
			text_area.text ="";
			text_area.alpha = 1;
			
			stopTimerShowParagraphTextRag();
			_paragraphText = text;
			
			timerShowParagraphTextRag = new Timer(25, text.length);
			timerShowParagraphTextRag.addEventListener(TimerEvent.TIMER, onTimerShowParagraphTextRag);
			timerShowParagraphTextRag.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerCompShowParagraphTextRag);
			timerShowParagraphTextRag.start();
			
			// タップしたらラグをエスケープする
			TapThenEscapeRag();
		}
		
		/**
		 * remove Listener
		 **/
		private function stopTimerShowParagraphTextRag():void{
			if(timerShowParagraphTextRag != null){
				timerShowParagraphTextRag.removeEventListener(TimerEvent.TIMER, onTimerShowParagraphTextRag);
				timerShowParagraphTextRag.removeEventListener(TimerEvent.TIMER_COMPLETE, onTimerCompShowParagraphTextRag);
				timerShowParagraphTextRag.stop();
				timerShowParagraphTextRag.reset();
				timerShowParagraphTextRag = null;
			}
			_paragraphTextNum = 0;
			_paragraphText = null;
		}
		
		/**
		 * delay毎に
		 **/
		private function onTimerShowParagraphTextRag(e:TimerEvent):void{
			text_area.text = _paragraphText.substr(0,_paragraphTextNum);
			_paragraphTextNum ++;
		}
		
		/**
		 * ラグが完了
		 **/
		private function onTimerCompShowParagraphTextRag(e:TimerEvent = null):void{
			stopTapListenForEscapeRag();
			
			text_area.text = _paragraphText;
			stopTimerShowParagraphTextRag();
			
			onSetParagraphText();
		}
		
		// タップしたらラグをエスケープする
		/**
		 * add Listener
		 **/
		private function TapThenEscapeRag():void{
			stopTapListenForEscapeRag()
			addEventListener(TouchEvent.TOUCH_TAP, onTapForEscapeRag);
			addEventListener(MouseEvent.CLICK, onTapForEscapeRag);
		}
		
		/**
		 * タップしたら
		 **/
		private function stopTapListenForEscapeRag():void{
			removeEventListener(TouchEvent.TOUCH_TAP, onTapForEscapeRag);
			removeEventListener(MouseEvent.CLICK, onTapForEscapeRag);
		}
		
		/**
		 * remove Listener
		 **/
		private function onTapForEscapeRag(e:Object):void{
			stopTapListenForEscapeRag();
			onTimerCompShowParagraphTextRag();
		}
		
		/**
		 * 表示が完了した時
		 **/
		private function onSetParagraphText():void{
			trace("\tonSetParagraphText");
				
			if(_is_pre_text){
				TapThenShowNextParagraphItem();
			}else if(_currentParagraphItem.type == "text"){
				TapThenShowNextParagraphItem();
			}else{
				showSelection();
			}
		}
		
		//
		private function showSelection():void{
			
			list.visible = true;
			_list_source = _currentParagraphItem.option;
			list.addEventListener(IndexChangeEvent.CHANGE, onADVCahange);
		}
		
		private function onADVCahange(e:IndexChangeEvent):void{
			trace(list.selectedIndex);
			var selected_option:ADV_SelectItemOption = _list_source.getItemAt(list.selectedIndex) as ADV_SelectItemOption;
			
			list.removeEventListener(IndexChangeEvent.CHANGE, onADVCahange);
			list.visible = false;
			_list_source = new ArrayCollection();
			
			trace(selected_option.selected_text);
			if(selected_option.selected_text != null && selected_option.selected_text.length > 0){
				showPreText(selected_option.selected_text, selected_option.goto_chapter_id, selected_option.goto_paragraph_id);
			}else{
				app_mng.story.goto(selected_option.goto_chapter_id, selected_option.goto_paragraph_id);
			}
		}
		
		private var _is_pre_text:Boolean = false;
		private var _next_chapter_id:String = null;
		private var _next_paragraph_id:String = null;
		private function showPreText(pre_text:String, next_chapter_id:String, next_paragraph_id:String):void{
			_is_pre_text = true;
			_next_chapter_id = next_chapter_id;
			_next_paragraph_id = next_paragraph_id;
			setParagraphText(pre_text);
		}
		
		private function onShowPreText():void{
			_is_pre_text = false;
			var next_chapter_id:String = _next_chapter_id;
			var next_paragraph_id:String = _next_paragraph_id;
			_next_chapter_id = null;
			_next_paragraph_id = null;
			app_mng.story.goto(next_chapter_id, _next_paragraph_id);
		}
	}
}